#!/bin/bash

BUILD_TOOL_ROOT=$(cd -- "$(dirname -- "$0")" && pwd -P)
while [ "$BUILD_TOOL_ROOT" != "/" ] && ! [ -e "$BUILD_TOOL_ROOT/.build-tool-root" ]; do
    BUILD_TOOL_ROOT="$(dirname "$BUILD_TOOL_ROOT")"
done
BUILD_TOOL_DEP_ROOT="$BUILD_TOOL_ROOT/../.build-tool-dep"
INSTALL_DIR="$BUILD_TOOL_ROOT/install"
REPO_BUILDED=""
CURR_DIR=$PWD

function print_title() {
    printf "%.s*" {1..80} && printf "\n"
    printf "* " && printf "$1" && printf "\n\n"
}

function build_guard() {
    repo=$1
    if [[ "$REPO_BUILDED" == *"|$repo|"* ]]; then
        return 1
    fi
    REPO_BUILDED+="|$repo|"
}

function check_repo() {
    repo=$1
    build_script="$BUILD_TOOL_ROOT/build-script/$repo.sh"
    if [[ ! -f $build_script ]]; then
        return 1
    fi
    repo_dir="$BUILD_TOOL_DEP_ROOT/$repo"
    if [[ ! -d $repo_dir ]]; then
        return 1
    fi
}

# Parse arguments.
to_build=()
for var in "$@"; do
    if [ "$var" = "-h" -o "$var" = "--help" ]; then
        echo "Usage: ./build.sh [options]"
        echo
        echo "Options:"
        echo "    --help               Display usage help"
        echo "    --all                Build all repos"
        echo "    repo_name            Build the specific repo"
        exit 1
    elif [ "$var" = "--all" ]; then
        to_build=()
        for f in ${BUILD_TOOL_ROOT}/build-script/*.sh; do
            repo=$(basename -- $f)
            repo=${repo::${#repo}-3}
            if [[ $repo != "base" && ${repo:0:1} != "." ]]; then
                check_repo $repo && to_build+=($repo)
            fi
        done
    else
        check_repo $var && to_build+=($var)
    fi
done

# Print global information.
print_title "Configure Build Tool"
echo "Setting BUILD_TOOL_ROOT to $BUILD_TOOL_ROOT"
if ! command -v "cmake" >/dev/null 2>&1; then
    echo "Could not find cmake."
    exit 1
else
    __CMAKE_INFO=$(cmake --system-information)
    echo "$__CMAKE_INFO" | grep -a --color=never "CMAKE_MINIMUM_REQUIRED_VERSION "
    echo "$__CMAKE_INFO" | grep -a --color=never "CMAKE_C_COMPILER =="
    echo "$__CMAKE_INFO" | grep -a --color=never "CMAKE_CXX_COMPILER =="
    echo "$__CMAKE_INFO" | grep -a --color=never "CMAKE_C_FLAGS =="
    echo "$__CMAKE_INFO" | grep -a --color=never "CMAKE_CXX_FLAGS =="
    echo "$__CMAKE_INFO" | grep -a --color=never "CMAKE_EXE_LINKER_FLAGS "
fi
echo "Building following libraries: ${to_build[@]}"
sleep 5 && echo

# Execute each script.
for repo in "${to_build[@]}"; do
    source "$BUILD_TOOL_ROOT/build-script/$repo.sh"
done

cd $CURR_DIR
